﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using SqlserverHelper;
using System.Threading;


using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using OJ;
using DLLmySQL;
using System.Text;
using System.IO;
using System.Web.DynamicData;

//查询品种分析
public partial class getDataPZFX : System.Web.UI.Page
{
    public string strCnn = ConfigurationSettings.AppSettings["DataBaseString"];
    protected void Page_Load(object sender, EventArgs e)
    {
        string shop_code = "";
        string class_id = "";
        string day_begin = "";
        string day_end = "";
        string shop_attr_name = "";
        string zx_status = "";
        string yb_status = "";
        string is_export = "false";
        string user_identity = "";

        if (Request.Form["shop_code"] != null && Request.Form["shop_code"].ToString().Trim() != "")
        {
            shop_code = Request.Form["shop_code"].ToString();
        }
        if (Request.Form["class_id"] != null && Request.Form["class_id"].ToString().Trim() != "")
        {
            class_id = Request.Form["class_id"].ToString();
        }
        if (Request.Form["day_begin"] != null && Request.Form["day_begin"].ToString().Trim() != "")
        {
            day_begin = Request.Form["day_begin"].ToString();
        }
        if (Request.Form["day_end"] != null && Request.Form["day_end"].ToString().Trim() != "")
        {
            day_end = Request.Form["day_end"].ToString();
        }
        if (Request.Form["shop_attr_name"] != null && Request.Form["shop_attr_name"].ToString().Trim() != "")
        {
            shop_attr_name = Request.Form["shop_attr_name"].ToString();
        }
        if (Request.Form["zx_status"] != null && Request.Form["zx_status"].ToString().Trim() != "")
        {
            zx_status = Request.Form["zx_status"].ToString();
        }
        if (Request.Form["yb_status"] != null && Request.Form["yb_status"].ToString().Trim() != "")
        {
            yb_status = Request.Form["yb_status"].ToString();
        }
        if (Request.Form["is_export"] != null && Request.Form["is_export"].ToString().Trim() != "")
        {
            is_export = Request.Form["is_export"].ToString();
        }
        if (Request.Form["user_identity"] != null && Request.Form["user_identity"].ToString().Trim() != "")
        {
            user_identity = Request.Form["user_identity"].ToString();
        }
        string stResult = f_getDataPZFX(shop_code, class_id, day_begin, day_end, shop_attr_name, zx_status, yb_status,is_export, user_identity);
        Response.Write(stResult);
    }

    public string f_getDataPZFX(string shop_code,string class_id, string day_begin, string day_end, string shop_attr_name, string zx_status, string yb_status, string is_export,string user_identity)
    {

        Define.retPZFX ret = new Define.retPZFX();
        List<Define.PZFX> L = new List<Define.PZFX>();
        List<Define.lineChartData> L1 = new List<Define.lineChartData>(); // 折线图1
        List<Define.lineChartData> L2 = new List<Define.lineChartData>(); // 折线图2
        List<Define.barChartData> B1 = new List<Define.barChartData>(); // 分类条形图
        List<Define.pieChartData> P1 = new List<Define.pieChartData>();//线上线下
        List<Define.pieChartData> P2 = new List<Define.pieChartData>();//医保/非医保
        List<Define.pieChartData> P3 = new List<Define.pieChartData>();//店铺属性
        //is_export = "true";
        try
        {
            // 查询条件
            string s = "";
            string s1 = "";
            string s2 = ""; // 条形码用bar
            
            //品种ID
            if (class_id != "")
            {
                s = s + " and class_id = '" + class_id.Trim() + "'";
                s1 = s1 + " and class_id = '" + class_id.Trim() + "'";
            }
            //日期
            if (day_begin == "" && day_end == "")
            {
                //s = s + " and DATE_FORMAT(ymd,'%Y-%m-%d') BETWEEN DATE_SUB(NOW(),INTERVAL 1 MONTH) AND NOW()";
                s = s + " and ymd >= DATE_SUB(CURDATE(),INTERVAL 1 MONTH) ";
                //s = s + " and DATE_FORMAT(ymd,'%Y-%m-%d') >= DATE_SUB(CURDATE(),INTERVAL 30 DAY) ";
                
            }
            if (day_begin != "")
            {
                s = s + " and ymd >= '" + day_begin.Trim() + " 00:00:00'";
            }
            if (day_end != "")
            {
                s = s + " and ymd <= '" + day_end.Trim() + " 23:59:59'";
            }
            //店铺名称
            if (shop_code != "")
            {
                s = s + " and dept_name = '" + shop_code.Trim() + "'";
                s1 = s1 + " and dept_name = '" + shop_code.Trim() + "'";
            }
            s2 = s; // 查询的where 条件（日期）

            //店铺属性
            if (shop_attr_name == "院边店")
            {
                s = s + " and shop_attr in(100,101,110,111)";
                s1 = s1 + " and shop_attr in(100,101,110,111)";
            }
            if (shop_attr_name == "社区店")
            {
                s = s + " and shop_attr in(010,011,110,111)";
                s1 = s1 + " and shop_attr in(100,101,110,111)";
            }
            if (shop_attr_name == "商业店")
            {
                s = s + " and shop_attr in(001,101,011,111)";
                s1 = s1 + " and shop_attr in(100,101,110,111)";
            }
            //线上线下
            if (zx_status == "线上")
            {
                s = s + " and pay_type in(219,209,216)"; //美团，饿百，微商城
                s1 = s1 + " and pay_type in(219,209,216)";
            }
            if (zx_status == "线下")
            {
                s = s + " and pay_type not in(219,209,216)"; //美团，饿百，微商城
                s1 = s1 + " and pay_type not in(219,209,216)";
            }
            //医保/非医保
            if (yb_status == "医保")
            {
                s = s + " and dept_name LIKE '%医保%'";
                s1 = s1 + " and dept_name LIKE '%医保%'";
            }
            if (yb_status == "非医保")
            {
                s = s + " and dept_name NOT LIKE '%医保%'";
                s1 = s1 + " and dept_name NOT LIKE '%医保%'";
            }

            //1 导出数据-所有明细
            // string strQuery = "SELECT DATE_FORMAT(ymd,'%Y-%m-%d'),dept_name,sell_qty,sell_price,age,sex,pay_type,shop_attr,(CASE WHEN dept_name LIKE '%医保%' THEN '医保店' ELSE '非医保店' END) yb_status FROM dsnfxcs WHERE 1=1 " + s;
            string strOutQuery = @"SELECT 
                                order_id as 销售单号,
                                ymd 销售日期,
                                dept_code 部门ID,
                                dept_name 部门名称,
                                class_id 品种ID,
                                prd_name 品名,
                                prd_spec 规格,
                                prd_unit 单位,
                                mfrs 生产厂商,
                                sell_qty 数量,
                                sell_price 含税金额,
                                dsnsklx.pay_type_name 支付类型,
                                age 年龄,
                                sex 性别,
                                (CASE shop_attr when '100' THEN '院边店' when '010' THEN '社区店' ELSE '商业店' END) 店铺属性,
                                (CASE WHEN dept_name LIKE '%医保%' THEN '医保店' ELSE '非医保店' END) 医保属性
                                FROM dsnfxcs 
                                left join dsnsklx on dsnfxcs.pay_type = dsnsklx.pay_type_id

                                WHERE 1=1 " + s
                                +  " order by ymd  ";

            // 2 导出数据-去掉重复数据（旧）
            string strOutQuery2 = @"SELECT DISTINCT
                                order_id as 销售单号,
                                ymd 销售日期,
                                dept_code 部门ID,
                                dept_name 部门名称,
                                class_id 品种ID,
                                prd_name 品名,
                                prd_spec 规格,
                                prd_unit 单位,
                                mfrs 生产厂商,
                                sell_qty 数量,
                                sell_price 含税金额,
                                
                                age 年龄,
                                sex 性别,
                                (CASE shop_attr when '100' THEN '院边店' when '010' THEN '社区店' ELSE '商业店' END) 店铺属性,
                                (CASE WHEN dept_name LIKE '%医保%' THEN '医保店' ELSE '非医保店' END) 医保属性
                                FROM dsnfxcs 

                                WHERE 1=1 " + s
                                + " order by ymd ";

            // 2 导出数据-去掉重复数据（新）
            strOutQuery2 = @"
                            SELECT 
                            order_id as 销售单号,
                            ymd 销售日期,
                            dept_code 部门ID,
                            dept_name 部门名称,
                            class_id 品种ID,
                            prd_name 品名,
                            prd_spec 规格,
                            prd_unit 单位,
                            mfrs 生产厂商,
                            sell_qty 数量,
                            sell_price 含税金额,
                            age 年龄,
                            sex 性别,
                            (CASE shop_attr when '100' THEN '院边店' when '010' THEN '社区店' ELSE '商业店' END) 店铺属性,
                            (CASE WHEN dept_name LIKE '%医保%' THEN '医保店' ELSE '非医保店' END) 医保属性
                            FROM dsnfxcs 
                            WHERE 1=1 " + s +
                            //and DATE_FORMAT(ymd,'%Y-%m-%d') >= DATE_SUB(CURDATE(),INTERVAL 7 DAY) 
                            @"GROUP BY
                            order_id ,
                            ymd ,
                            dept_code ,
                            dept_name ,
                            class_id ,
                            prd_name ,
                            prd_spec ,
                            prd_unit ,
                            mfrs ,
                            sell_qty ,
                            sell_price ,

                            age ,
                            sex ,
                            shop_attr,
                            dept_name
                            HAVING count(distinct pay_type) > 1 "
                            + " order by ymd ";



            string outputFile = ""; 
            string outputUrl = "https://" + Request.Url.Authority;
            if (is_export == "true")
            {
                OperLog.log("品种分析-导出", user_identity);

                LogBLL.log("【品种分析】【导出数据-所有明细】" + strOutQuery);
                LogBLL.log("【品种分析】【导出数据-去掉重复数据（新）】" + strOutQuery2);
                DataTable DT_out = CmySQL.GetDataTbale(strCnn, strOutQuery);
                DataTable DT_out2 = CmySQL.GetDataTbale(strCnn, strOutQuery2);
                if (DT_out != null && DT_out.Rows.Count > 0)
                {
                    /*for (int i = 0; i < DT.Rows.Count; i++)
                    {
                        Define.PZFX r = new Define.PZFX();
                        r.order_id = DT.Rows[i]["order_id"].ToString().Trim();
                        r.ymd = DT.Rows[i]["ymd"].ToString().Trim();
                        r.dept_code = DT.Rows[i]["dept_code"].ToString().Trim();
                        r.dept_name = DT.Rows[i]["dept_name"].ToString().Trim();
                        r.class_id = DT.Rows[i]["class_id"].ToString().Trim();
                        r.prd_code = DT.Rows[i]["prd_code"].ToString().Trim();
                        r.prd_name = DT.Rows[i]["prd_name"].ToString().Trim();
                        r.prd_spec = DT.Rows[i]["prd_spec"].ToString().Trim();
                        r.prd_unit = DT.Rows[i]["prd_unit"].ToString().Trim();
                        r.mfrs = DT.Rows[i]["mfrs"].ToString().Trim();
                        r.sell_qty = DT.Rows[i]["sell_qty"].ToString().Trim();
                        r.sell_price = DT.Rows[i]["sell_price"].ToString().Trim();
                        r.pay_type = DT.Rows[i]["pay_type"].ToString().Trim();
                        r.age = DT.Rows[i]["age"].ToString().Trim();
                        r.sex = DT.Rows[i]["sex"].ToString().Trim();
                        r.shop_attr = DT.Rows[i]["shop_attr"].ToString().Trim();
                        r.yb_status = DT.Rows[i]["yb_status"].ToString().Trim();
                        L.Add(r);

                    }*/
                }

                string fileName = "out_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
                outputFile = AppDomain.CurrentDomain.BaseDirectory + "out\\" + fileName;
                outputUrl = outputUrl + "/api_sst/out" + "/" + fileName;
                // ExportToCsv(DT_out, DT_out2, outputFile);

                //string sFileName = @"D:\out\" + "out_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx"; // 将YourDirectory替换为您想要的目录名，yourfile.xlsx是文件名
                string sFileName = outputFile; // 将YourDirectory替换为您想要的目录名，yourfile.xlsx是文件名

                // 确保目录存在，如果不存在则创建
                string directoryPath = Path.GetDirectoryName(sFileName);
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                }


                //ExcelHelper.TableToExcel(DT_out, "out_" + DateTime.Now.ToString("yyyyMMddhhmmss")+ ".xlsx");
                List<DataTable> dtList = new List<DataTable>();
                if (DT_out == null) DT_out = new DataTable();
                if (DT_out2 == null) DT_out2 = new DataTable();

                DT_out.TableName = "所有明细数据";
                DT_out2.TableName = "可合并数据";
                dtList.Add(DT_out);
                dtList.Add(DT_out2);
                DataTable[] dtSources = dtList.ToArray();
                //ExcelHelper.ExportDTtoExcel(DT_out, "out_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx", true);
                //ExcelHelper.ExportDTtoExcel(DT_out, sFileName, true);
                ExcelHelper.ExportDTtoExcelXS(dtSources, sFileName, true,"");


            }
            else {
                outputUrl = "";

                OperLog.log("品种分析-查询", user_identity);


                //2,最近7天趋势图 七日客单价（客单价 = 合计金额/笔数）
                //string strQuery1 = "SELECT DATE_FORMAT(ymd,'%Y-%m-%d'),SUM(sell_price) amt FROM  dsnfxcs WHERE DATE_FORMAT(ymd,'%Y-%m-%d') >= DATE_SUB(CURDATE(),INTERVAL 7 DAY) " + s1 + " GROUP BY DATE_FORMAT(ymd,'%Y-%m-%d')";
                string strQuery1 =
                    " SELECT DATE_FORMAT(a.ymd,'%Y-%m-%d'),SUM(a.sell_price) amt,count(distinct order_id) order_cnt " +
                    " FROM  ( "+
                    " select  "+
                    "   distinct  "+
                    "   order_id, "+
                    "   ymd, "+
                    "   dept_code, "+
                    "   dept_name, "+
                    "   class_id, "+
                    "   prd_code, "+
                    "   prd_name, "+
                    "   prd_spec, "+
                    "   prd_unit, "+
                    "   mfrs, "+
                    "   tax_rate, " +
                    "   sell_qty, "+
                    "   sell_price, "+
                    "   sell_amt, "+
                    "   age, "+
                    "   sex, "+
                    "   shop_attr from dsnfxcs "+
                    "   where 1=1  "+ s2 +
                    // "   and DATE_FORMAT(ymd,'%Y-%m-%d') >= DATE_SUB(CURDATE(),INTERVAL 7 DAY) "+

                    " ) a "+
                    " WHERE 1=1  "+
                    "  GROUP BY DATE_FORMAT(a.ymd,'%Y-%m-%d') "+
                    "";
                LogBLL.log("【品种分析】【日销售额走势】" + strQuery1);
                //LogBLL.log("【品种分析】【七日客单价】" + strQuery1);
                DataTable DT1 = CmySQL.GetDataTbale(strCnn, strQuery1);
                if (DT1 != null && DT1.Rows.Count > 0)
                {
                    for (int i = 0; i < DT1.Rows.Count; i++)
                    {
                        Define.lineChartData r1 = new Define.lineChartData();
                        r1.name = DT1.Rows[i][0].ToString().Trim(); // 时间段
                        // 日销售额
                        r1.data = Math.Round(System.Convert.ToDecimal(DT1.Rows[i][1].ToString().Trim()) / System.Convert.ToDecimal(DT1.Rows[i][2].ToString().Trim()), 2).ToString();
                        // 销售量
                        r1.data2 = DT1.Rows[i][2].ToString().Trim();
                        // 客单价
                        //r1.data = Math.Round(System.Convert.ToDecimal(DT1.Rows[i][1].ToString().Trim()) / System.Convert.ToDecimal(DT1.Rows[i][2].ToString().Trim()), 2).ToString();
                        


                        L1.Add(r1);
                    }
                }

                // 时间段销售额走势
                string strQuery12 = "";
                strQuery12 = " select hour(ymd) h,SUM(sell_price) amt,count(distinct order_id) order_cnt " +
                            " from dsnfxcs where 1=1 " + s2 + 
                            //" AND DATE_FORMAT(ymd,'%Y-%m-%d') >= DATE_SUB(CURDATE(),INTERVAL 7 DAY) " +                            
                            " and hour(ymd) >=8  " +
                            " and hour(ymd) <=21 " +
                            " GROUP BY hour(ymd) " +
                                "";

                LogBLL.log("【品种分析】【时间段销售额走势】" + strQuery12);
                DataTable DT12 = CmySQL.GetDataTbale(strCnn, strQuery12);
                if (DT12 != null && DT12.Rows.Count > 0)
                {
                    for (int i = 0; i < DT12.Rows.Count; i++)
                    {
                        Define.lineChartData r1 = new Define.lineChartData();
                        r1.name = DT12.Rows[i]["h"].ToString().Trim();              // 时间段
                        r1.data = DT12.Rows[i]["amt"].ToString().Trim();            // 销售额
                        r1.data2 = DT12.Rows[i]["order_cnt"].ToString().Trim();     // 销售量
                        L2.Add(r1);
                    }
                }


                // 条形图
                string strSQL = "";
                strSQL += "         SELECT '线上' name , COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs where pay_type IN(219,209,216)  " + s2;
                strSQL += " UNION SELECT '线下'   name , COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs where pay_type NOT IN(219,209,216)  " + s2;
                strSQL += " UNION SELECT '医保'   name , COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs WHERE dept_name LIKE '%医保%' " + s2;
                strSQL += " UNION SELECT '非医保' name, COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs WHERE dept_name NOT LIKE '%医保%'  " + s2;
                strSQL += " UNION SELECT '院边店' name, COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs WHERE SUBSTRING(shop_attr,1,1) = 1 " + s2;
                strSQL += " UNION SELECT '社区店' name, COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs WHERE SUBSTRING(shop_attr,2,1) = 1 " + s2;
                strSQL += " UNION SELECT '商业店' name, COUNT(*) cnt,IFNULL(SUM(sell_price),0) amt FROM dsnfxcs WHERE SUBSTRING(shop_attr,3,1) = 1 " + s2;

                LogBLL.log("【品种分析】【分类条形图】" + strSQL);
                DataTable DT_bar = CmySQL.GetDataTbale(strCnn, strSQL);
                if (DT_bar != null && DT_bar.Rows.Count > 0)
                {
                    for (int i = 0; i < DT_bar.Rows.Count; i++)
                    {
                        Define.barChartData bar = new Define.barChartData();
                        bar.name = DT_bar.Rows[i]["name"].ToString().Trim();              // 时间段
                        bar.data = DT_bar.Rows[i]["amt"].ToString().Trim();            // 销售额
                        bar.data2 = DT_bar.Rows[i]["cnt"].ToString().Trim();     // 销售量
                        B1.Add(bar);
                    }
                }


                //线上
                string strQuery2 = "SELECT COUNT(*) FROM dsnfxcs where pay_type IN(219,209,216) " + s;
                //线下
                string strQuery3 = "SELECT COUNT(*) FROM dsnfxcs where pay_type NOT IN(219,209,216) " + s;
                LogBLL.log("【品种分析】【线上】" + strQuery2);
                LogBLL.log("【品种分析】【线下】" + strQuery3);
                DataTable DT2 = CmySQL.GetDataTbale(strCnn, strQuery2);
                DataTable DT3 = CmySQL.GetDataTbale(strCnn, strQuery3);

                Define.pieChartData p1 = new Define.pieChartData() { name = "线上", data = DT2.Rows[0][0] };
                Define.pieChartData p2 = new Define.pieChartData() { name = "线下", data = DT3.Rows[0][0] };
                P1.Add(p1);
                P1.Add(p2);


                //医保
                string strQuery4 = "SELECT COUNT(*) FROM dsnfxcs WHERE dept_name LIKE'%医保%' " + s;
                //非医保
                string strQuery5 = "SELECT COUNT(*) FROM dsnfxcs WHERE dept_name NOT LIKE'%医保%' " + s;

                LogBLL.log("【品种分析】【医保】" + strQuery4);
                LogBLL.log("【品种分析】【非医保】" + strQuery5);
                DataTable DT4 = CmySQL.GetDataTbale(strCnn, strQuery4);
                DataTable DT5 = CmySQL.GetDataTbale(strCnn, strQuery5);

                Define.pieChartData p3 = new Define.pieChartData() { name = "医保", data = DT4.Rows[0][0] };
                Define.pieChartData p4 = new Define.pieChartData() { name = "非医保", data = DT5.Rows[0][0] };
                P2.Add(p3);
                P2.Add(p4);


                ////店铺属性(院边店，社区店，商业店)
                string strQuery6 = "SELECT COUNT(*) FROM dsnfxcs WHERE SUBSTRING(shop_attr,1,1) = 1 " + s;
                string strQuery7 = "SELECT COUNT(*) FROM dsnfxcs WHERE SUBSTRING(shop_attr,2,1) = 1 " + s;
                string strQuery8 = "SELECT COUNT(*) FROM dsnfxcs WHERE SUBSTRING(shop_attr,3,1) = 1 " + s;

                LogBLL.log("【品种分析】【店铺属性】" + strQuery6);
                LogBLL.log("【品种分析】【店铺属性】" + strQuery7);
                LogBLL.log("【品种分析】【店铺属性】" + strQuery8);
                DataTable DT6 = CmySQL.GetDataTbale(strCnn, strQuery6);
                DataTable DT7 = CmySQL.GetDataTbale(strCnn, strQuery7);
                DataTable DT8 = CmySQL.GetDataTbale(strCnn, strQuery8);

                Define.pieChartData p5 = new Define.pieChartData() { name = "院边店", data = DT5.Rows[0][0] };
                Define.pieChartData p6 = new Define.pieChartData() { name = "社区店", data = DT6.Rows[0][0] };
                Define.pieChartData p7 = new Define.pieChartData() { name = "商业店", data = DT8.Rows[0][0] };
                P3.Add(p5);
                P3.Add(p6);
                P3.Add(p7);
            }

            ret.code = 200;
            ret.msg = "success" + is_export;

            ret.data = L;
            ret.lineChartData = L1;
            ret.lineChartData2 = L2;
            ret.barChartData = B1;
            ret.zx_pieChartData = P1;
            ret.yb_pieChartData = P2;       
            ret.dp_pieChartData = P3;
            ret.outputUrl = outputUrl;
        }
        catch (Exception e)
        {
            LogBLL.log(e.ToString());
            string er = e.Message;
            ret.code = 20000;
            ret.msg = er;
            ret.data = null;
            ret.lineChartData = null;
            ret.yb_pieChartData = null;
            ret.zx_pieChartData = null;
            ret.dp_pieChartData = null;
        }

        return Ojson.ObjectToJson(ret);
    }

    /// <summary>
    /// DataTable导出成CSV文件
    /// </summary>
    /// <param name="dataTable">数据集</param>
    /// <param name="filePath">导出文件地址</param>
    public void ExportToCsv(DataTable dataTable, DataTable dataTable2, string filePath)
    {
        StringBuilder sb = new StringBuilder();

        // dt1
        foreach (DataColumn col in dataTable.Columns)
        {
            sb.Append(col.ColumnName + ",");
        }
        //sb.Append("进货");
        //sb.Append("销售单号,销售日期,部门ID,部门名称,分类id,商品ID,品名,规格,单位,生产厂商.税率,数量,含税金额（合计）,支付类型,年龄,性别,线上/线下,店铺属性,医保/非医保");  //时间
        sb.AppendLine();

        foreach (DataRow row in dataTable.Rows)
        {
            foreach (DataColumn col in dataTable.Columns)
            {
                sb.Append(row[col].ToString().Replace(",", " ") + ",");
            }
            sb.AppendLine();
        }

        // dt2
        sb.AppendLine();
        sb.AppendLine();
        sb.Append("明细");
        sb.AppendLine();
        foreach (DataColumn col in dataTable2.Columns)
        {
            sb.Append(col.ColumnName + ",");
        }
        sb.AppendLine();

        foreach (DataRow row in dataTable2.Rows)
        {
            foreach (DataColumn col in dataTable2.Columns)
            {
                sb.Append(row[col].ToString().Replace(",", " ") + ",");
            }
            sb.AppendLine();
        }

        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.Write(sb.ToString());
        }
    }

    /*public void ExportToCsv(DataTable dataTable, string filePath)
    {
        StringBuilder sb = new StringBuilder();
        foreach (DataColumn col in dataTable.Columns)
        {
            sb.Append(col.ColumnName + ",");
        }
        sb.AppendLine();
        foreach (DataRow row in dataTable.Rows)
        {
            foreach (DataColumn col in dataTable.Columns)
            {
                sb.Append(row[col].ToString() + ",");
            }
            sb.AppendLine();
        }
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.Write(sb.ToString());
        }
    }*/
}